package cn.yueranzs.system.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.yueranzs.handler.BusinessException;
import cn.yueranzs.response.Result;
import cn.yueranzs.response.ResultCode;
import cn.yueranzs.response.UrlResultCode;
import cn.yueranzs.response.UserResultCode;
import cn.yueranzs.system.dto.useravatar.UserAvatarChangeDto;
import cn.yueranzs.system.service.UserAvatarService;
import cn.yueranzs.utils.AliyunOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author yueranzs
 * @date 2021-11-12 15:32
 */
@Api(tags = "用户头像控制器")
@RestController
@RequestMapping("/user-avator")
public class UserAvatarController {

    @Resource
    private UserAvatarService userAvatarService;

    @ApiOperation("上传用户头像")
    @PostMapping("insertUserAvatar")
    public Result insertUserAvatar(UserAvatarChangeDto dto){
        if (ObjectUtil.isEmpty(dto.getImgFile())) {
            return Result.error(UserResultCode.USER_NOT_HEADPORTRAIT.getCode(),UserResultCode.USER_NOT_HEADPORTRAIT.getMessage());
        }
        try {
            String filePath = AliyunOSSUtil.uploadFile(dto.getImgFile(), UrlResultCode.HEAD_PORTRAIT_URL.getMessage() + "/" + "temp");
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("avatar",filePath);
            jsonObject.set("avatarUrl",AliyunOSSUtil.getFileUrl(filePath,null));
            return Result.successData(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }catch (BusinessException e){
            return Result.error(e.getCode(),e.getErrMsg());
        }
        return Result.error(ResultCode.SAVEERROR.getCode(),ResultCode.SAVEERROR.getMessage());
    }
    @ApiOperation("修改用户头像")
    @PostMapping("updateUserAvatar")
    public Result updateUserAvatar(UserAvatarChangeDto dto){
        if (ObjectUtil.isEmpty(dto.getId())) {
            return Result.error(UserResultCode.USER_NOT_ID.getCode(),UserResultCode.USER_NOT_ID.getMessage());
        }
        if (ObjectUtil.isEmpty(dto.getImgFile())) {
            return Result.error(UserResultCode.USER_NOT_HEADPORTRAIT.getCode(),UserResultCode.USER_NOT_HEADPORTRAIT.getMessage());
        }
        try {
            JSONObject jsonObject = userAvatarService.updateUserAvatar(dto);
            return Result.successData(jsonObject);
        }catch (BusinessException e){
            return Result.error(e.getCode(),e.getErrMsg());
        }
    }

}
